{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#协同过滤推荐算法简单代码实现（基于物品皮尔逊相关系数）\n",
    "#评分预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from pprint import pprint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       ItemA  ItemB  ItemC  ItemD  ItemE\n",
      "User1      5      3      4      4    NaN\n",
      "User2      3      1      2      3    3.0\n",
      "User3      4      3      4      3    5.0\n",
      "User4      3      3      1      5    4.0\n",
      "User5      1      5      5      2    1.0\n",
      "Index(['User1', 'User2', 'User3', 'User4', 'User5'], dtype='object')\n",
      "Index(['ItemA', 'ItemB', 'ItemC', 'ItemD', 'ItemE'], dtype='object')\n"
     ]
    }
   ],
   "source": [
    "#构建用户购买记录数据集（打分）\n",
    "users = [\"User1\",\"User2\",\"User3\",\"User4\",\"User5\",]\n",
    "items = [\"ItemA\",\"ItemB\",\"ItemC\",\"ItemD\",\"ItemE\"]\n",
    "datasets = [\n",
    "    [5,3,4,4,None],\n",
    "    [3,1,2,3,3],\n",
    "    [4,3,4,3,5],\n",
    "    [3,3,1,5,4],\n",
    "    [1,5,5,2,1],\n",
    "]\n",
    "#预测User1对E商品的打分\n",
    "df = pd.DataFrame(datasets,columns=items,index=users)\n",
    "print(df)\n",
    "print(df.index)\n",
    "print(df.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "物品之间的相似度\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>User1</th>\n",
       "      <th>User2</th>\n",
       "      <th>User3</th>\n",
       "      <th>User4</th>\n",
       "      <th>User5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>User1</th>\n",
       "      <td>1.0000</td>\n",
       "      <td>0.8528</td>\n",
       "      <td>0.7071</td>\n",
       "      <td>0.0000</td>\n",
       "      <td>-0.7921</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>User2</th>\n",
       "      <td>0.8528</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>0.4677</td>\n",
       "      <td>0.4900</td>\n",
       "      <td>-0.9001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>User3</th>\n",
       "      <td>0.7071</td>\n",
       "      <td>0.4677</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>-0.1612</td>\n",
       "      <td>-0.4666</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>User4</th>\n",
       "      <td>0.0000</td>\n",
       "      <td>0.4900</td>\n",
       "      <td>-0.1612</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>-0.6415</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>User5</th>\n",
       "      <td>-0.7921</td>\n",
       "      <td>-0.9001</td>\n",
       "      <td>-0.4666</td>\n",
       "      <td>-0.6415</td>\n",
       "      <td>1.0000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        User1   User2   User3   User4   User5\n",
       "User1  1.0000  0.8528  0.7071  0.0000 -0.7921\n",
       "User2  0.8528  1.0000  0.4677  0.4900 -0.9001\n",
       "User3  0.7071  0.4677  1.0000 -0.1612 -0.4666\n",
       "User4  0.0000  0.4900 -0.1612  1.0000 -0.6415\n",
       "User5 -0.7921 -0.9001 -0.4666 -0.6415  1.0000"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算用户间相似度 默认是列\n",
    "user_similar = df.T.corr()\n",
    "print(\"物品之间的相似度\")\n",
    "user_similar.round(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "物品之间的相似度\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>ItemA</th>\n",
       "      <th>ItemB</th>\n",
       "      <th>ItemC</th>\n",
       "      <th>ItemD</th>\n",
       "      <th>ItemE</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>ItemA</th>\n",
       "      <td>1.0000</td>\n",
       "      <td>-0.4767</td>\n",
       "      <td>-0.1231</td>\n",
       "      <td>0.5322</td>\n",
       "      <td>0.9695</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ItemB</th>\n",
       "      <td>-0.4767</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>0.6455</td>\n",
       "      <td>-0.3101</td>\n",
       "      <td>-0.4781</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ItemC</th>\n",
       "      <td>-0.1231</td>\n",
       "      <td>0.6455</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>-0.7206</td>\n",
       "      <td>-0.4276</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ItemD</th>\n",
       "      <td>0.5322</td>\n",
       "      <td>-0.3101</td>\n",
       "      <td>-0.7206</td>\n",
       "      <td>1.0000</td>\n",
       "      <td>0.5817</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>ItemE</th>\n",
       "      <td>0.9695</td>\n",
       "      <td>-0.4781</td>\n",
       "      <td>-0.4276</td>\n",
       "      <td>0.5817</td>\n",
       "      <td>1.0000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        ItemA   ItemB   ItemC   ItemD   ItemE\n",
       "ItemA  1.0000 -0.4767 -0.1231  0.5322  0.9695\n",
       "ItemB -0.4767  1.0000  0.6455 -0.3101 -0.4781\n",
       "ItemC -0.1231  0.6455  1.0000 -0.7206 -0.4276\n",
       "ItemD  0.5322 -0.3101 -0.7206  1.0000  0.5817\n",
       "ItemE  0.9695 -0.4781 -0.4276  0.5817  1.0000"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算商品间相似度默认是列\n",
    "item_similar = df.corr()\n",
    "print(\"物品之间的相似度\")\n",
    "item_similar.round(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User1最相似的两个用户\n",
      "['User2', 'User3']\n",
      "使用用户间的相似度进行预测：Use1给ItemE打：\n",
      "3.9065996645686396\n"
     ]
    }
   ],
   "source": [
    "item = \"ItemE\"\n",
    "user = \"User1\"\n",
    "#基于用户评分\n",
    "_df = user_similar.loc[user].drop(user)\n",
    "_df_sorted = _df.sort_values(ascending = False)  \n",
    "sim_users = list(_df_sorted.index[:2])\n",
    "print(\"User1最相似的两个用户\")\n",
    "pprint(sim_users)\n",
    "\n",
    "sum1 = 0\n",
    "sum2 = 0\n",
    "for sim_user in sim_users:\n",
    "    sum1 += df.loc[sim_user].loc[item] * user_similar.loc[user].loc[sim_user]\n",
    "    sum2 += user_similar.loc[user].loc[sim_user]\n",
    "\n",
    "print(\"使用用户间的相似度进行预测：Use1给ItemE打：\")\n",
    "print(sum1/sum2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ItemE最相似的两个商品\n",
      "['ItemA', 'ItemD']\n",
      "使用商品间的相似度进行预测：Use1给ItemE打：\n",
      "4.625\n"
     ]
    }
   ],
   "source": [
    "#基于商品评分\n",
    "_df = item_similar.loc[item].drop(item)\n",
    "_df_sorted = _df.sort_values(ascending = False)  \n",
    "sim_items = list(_df_sorted.index[:2])\n",
    "print(\"ItemE最相似的两个商品\")\n",
    "pprint(sim_items)\n",
    "\n",
    "sum1 = 0\n",
    "sum2 = 0\n",
    "for sim_item in sim_items:\n",
    "    sum1 += df.loc[user].loc[sim_item] * item_similar.loc[item].loc[sim_item]\n",
    "    sum2 += item_similar.loc[item].loc[sim_item]\n",
    "    \n",
    "print(\"使用商品间的相似度进行预测：Use1给ItemE打：\")\n",
    "print(sum1/sum2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
